package com.tsj.model.utils;

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import java.io.*;

public class ExcelAttachmentExtractor2 {

    public static void main(String[] args) {
        String excelFile = "S://1.xlsx";
        String outputDir = "S://";

        extractAttachments(excelFile, outputDir);
    }

    public static void extractAttachments(String excelFilePath, String outputDir) {
        try (FileInputStream file = new FileInputStream(new File(excelFilePath))) {
            Workbook workbook = WorkbookFactory.create(file);

            System.out.println("开始提取 Excel 文件中的嵌入对象...");

            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                String sheetName = workbook.getSheetName(i);
                System.out.println("处理工作表: " + sheetName);

                extractAttachmentsFromSheet(sheet, outputDir, sheetName);
            }

            workbook.close();
            System.out.println("提取完成！");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void extractAttachmentsFromSheet(Sheet sheet, String outputDir, String sheetName) {
        if (sheet instanceof XSSFSheet) {
            XSSFSheet xssfSheet = (XSSFSheet) sheet;
            XSSFDrawing drawing = xssfSheet.getDrawingPatriarch();

            if (drawing == null) {
                System.out.println("  - 未找到嵌入对象");
                return;
            }

            int objectCount = 0;
            for (XSSFShape shape : drawing.getShapes()) {
                if (shape instanceof XSSFPicture) {
                    extractPicture((XSSFPicture) shape, outputDir, sheetName, ++objectCount);
                } else if (shape instanceof XSSFObjectData) {
                    extractOleObject((XSSFObjectData) shape, outputDir, sheetName, ++objectCount);
                }
            }

            if (objectCount == 0) {
                System.out.println("  - 未找到可提取的对象");
            }
        }
    }

    private static void extractPicture(XSSFPicture picture, String outputDir, String sheetName, int count) {
        try {
            XSSFPictureData pictureData = picture.getPictureData();
            byte[] data = pictureData.getData();
            String extension = pictureData.suggestFileExtension();
            String fileName = sheetName + "_picture_" + count + "." + extension;

            saveToFile(data, outputDir, fileName);
            System.out.println("  ✓ 保存图片: " + fileName);

        } catch (Exception e) {
            System.err.println("  ✗ 提取图片失败");
            e.printStackTrace();
        }
    }

    private static void extractOleObject(XSSFObjectData objectData, String outputDir, String sheetName, int count) {
        try {
            String oleName = objectData.getFileName();
            byte[] data = objectData.getObjectData();

            String extension = getFileExtension(oleName);
            if (extension.isEmpty()) {
                extension = "bin";
            }

            String fileName = sheetName + "_file_" + count + "." + extension;
            saveToFile(data, outputDir, fileName);
            System.out.println("  ✓ 保存嵌入文件: " + fileName + " (原始: " + oleName + ")");

        } catch (Exception e) {
            System.err.println("  ✗ 提取嵌入文件失败");
            e.printStackTrace();
        }
    }

    private static String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        return (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1)
                ? fileName.substring(lastDotIndex + 1).toLowerCase() : "";
    }

    private static void saveToFile(byte[] data, String outputDir, String fileName) {
        try {
            File dir = new File(outputDir);
            if (!dir.exists()) dir.mkdirs();

            File outputFile = new File(dir, fileName);
            try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                fos.write(data);
            }
        } catch (IOException e) {
            System.err.println("保存文件失败: " + fileName);
            e.printStackTrace();
        }
    }
}